import {makeAutoObservable} from 'mobx';
import axios from 'axios'


class appleStore {
    constructor(){
        makeAutoObservable(this,{},{autoBind:true})
    }

    apples = [
        {
            id: 0,
            weight: 233,
            isEaten: false
        },
        {
            id: 1,
            weight: 235,
            isEaten: false
        },
        {
            id: 2,
            weight: 256,
            isEaten: false
        }
    ];
    newAppleId = 3;
    isPicking = false;
    buttonText = '摘苹果';




    /**  计算当前已吃和未吃苹果的状态 */
    get status(){
        let status = {
            appleNow: {
                quantity: 0,
                weight: 0
            },
            appleEaten: {
                quantity: 0,
                weight: 0
            }
        };
        this.apples.forEach(apple => {
            let selector = apple.isEaten ? 'appleEaten':'appleNow';
            status[selector].quantity ++;
            status[selector].weight += apple.weight;
        });
        return status;
    }


    /*摘苹果的异步操作*/
    pickApple = ()=>{

        /** 如果正在摘苹果，则结束这个thunk, 不执行摘苹果 */
        if (this.isPicking) {
            return;
        }

        this.isPicking = true;
        this.buttonText = '正在采摘...';
        axios.get('http://localhost:3005/data').then(
            res => {
                this.isPicking = false;
                this.buttonText = '摘苹果';
                res.data[0].id = this.newAppleId++;
                this.apples.push(res.data[0]);
            }
        )
    }
    /* 这里需要写成箭头函数的形式，这样此函数从父组件传递到子组件的时候才能调用成功*/
    eatApple = (appleId)=>{

        let targetIndex = '';
        this.apples.forEach((apple,index)=>{
            if(apple.id === appleId){
                targetIndex = index
            }
        });
        this.apples[targetIndex].isEaten = true;
    }




}

export default appleStore;